//导入axios
import axios from 'axios'
import $router from '../router/index'
import { Toast } from 'vant';

//设置请求拦截器
axios.interceptors.request.use((config)=>{
    //给请求头 携带token
    config.headers['Authorization'] = 'Bearer ' + localStorage.getItem('token');
    //config.headers['X-Token'] = 'Bearer ' + localStorage.getItem('token');

    return config;
},(error)=>{
    return Promise.reject(error);
})

//设置响应拦截器
axios.interceptors.response.use((res)=>{
    
    return res;
},(error)=>{
    //处理响应错误码
    if( error.response.status == 401 ){
        Toast.fail('登录过期,身份验证失败!')
        //删除token
        localStorage.removeItem('token');
        //跳转到登录页,重新登录
        $router.push('/login');
        
    }else if( error.response.status == 404 ){
        Toast.fail('访问路径有误');
    }else if( error.response.status == 500 ){
        Toast.fail('服务器内部错误');
        
    }

    return Promise.reject(error);
})

//导出axios
export default axios;